const { pool } = require('../models/db'); 
const { validationResult } = require('express-validator');

async function getHallRankings(req, res) {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { sortBy = 'dataValue', period = 'week' } = req.query;
    
    const validTypes = ['dataValue', 'count', 'growth'];
    if (!validTypes.includes(sortBy)) {
      return res.status(400).json({ error: '无效的排序类型，允许的值：dataValue, count, growth' });
    }

    let timeCondition = '';
    const now = new Date();
    const pastDate = new Date();
    
    switch (period) {
      case 'day':
        pastDate.setDate(now.getDate() - 1);
        break;
      case 'week':
        pastDate.setDate(now.getDate() - 7);
        break;
      case 'month':
        pastDate.setMonth(now.getMonth() - 1);
        break;
      case 'year':
        pastDate.setFullYear(now.getFullYear() - 1);
        break;
      default:
        break;
    }
    
    if (period !== 'all') {
      timeCondition = `WHERE upload_time >= '${pastDate.toISOString()}'`;
    }

    let query;
    switch (sortBy) {
      case 'dataValue':
        query = `
          SELECT hall_name, SUM(data_value) as total_value, COUNT(*) as record_count
          FROM data_records
          ${timeCondition}
          GROUP BY hall_name
          ORDER BY total_value DESC
        `;
        break;
      case 'count':
        query = `
          SELECT hall_name, COUNT(*) as record_count, SUM(data_value) as total_value
          FROM data_records
          ${timeCondition}
          GROUP BY hall_name
          ORDER BY record_count DESC
        `;
        break;
      case 'growth':
        query = `
          SELECT hall_name, SUM(data_value) as total_value, COUNT(*) as record_count
          FROM data_records
          ${timeCondition}
          GROUP BY hall_name
          ORDER BY (SUM(data_value)/COUNT(*)) DESC
        `;
        break;
    }

    const [rankings] = await pool.query(query);

    const result = rankings.map((item, index) => ({
      rank: index + 1,
      hallName: item.hall_name,
      totalValue: parseFloat(item.total_value),
      recordCount: parseInt(item.record_count),
      averageValue: parseFloat((item.total_value / item.record_count).toFixed(2))
    }));

    res.json({
      period,
      sortBy,
      count: result.length,
      rankings: result
    });
  } catch (error) {
    console.error('获取厅名排行榜失败:', error);
    res.status(500).json({ error: '获取排行榜数据失败: ' + error.message });
  }
}

async function getHostRankings(req, res) {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { sortBy = 'dataValue', period = 'week' } = req.query;
    
    const validTypes = ['dataValue', 'count', 'hallCount'];
    if (!validTypes.includes(sortBy)) {
      return res.status(400).json({ error: '无效的排序类型，允许的值：dataValue, count, hallCount' });
    }

    let timeCondition = '';
    const now = new Date();
    const pastDate = new Date();
    
    switch (period) {
      case 'day':
        pastDate.setDate(now.getDate() - 1);
        break;
      case 'week':
        pastDate.setDate(now.getDate() - 7);
        break;
      case 'month':
        pastDate.setMonth(now.getMonth() - 1);
        break;
      case 'year':
        pastDate.setFullYear(now.getFullYear() - 1);
        break;
      default:
        break;
    }
    
    if (period !== 'all') {
      timeCondition = `WHERE upload_time >= '${pastDate.toISOString()}'`;
    }

    let query;
    switch (sortBy) {
      case 'dataValue':
        query = `
          SELECT host_name, SUM(data_value) as total_value, COUNT(*) as record_count, COUNT(DISTINCT hall_name) as hall_count
          FROM data_records
          ${timeCondition}
          GROUP BY host_name
          ORDER BY total_value DESC
        `;
        break;
      case 'count':
        query = `
          SELECT host_name, COUNT(*) as record_count, SUM(data_value) as total_value, COUNT(DISTINCT hall_name) as hall_count
          FROM data_records
          ${timeCondition}
          GROUP BY host_name
          ORDER BY record_count DESC
        `;
        break;
      case 'hallCount':
        query = `
          SELECT host_name, COUNT(DISTINCT hall_name) as hall_count, SUM(data_value) as total_value, COUNT(*) as record_count
          FROM data_records
          ${timeCondition}
          GROUP BY host_name
          ORDER BY hall_count DESC
        `;
        break;
    }

    const [rankings] = await pool.query(query);

    const result = rankings.map((item, index) => ({
      rank: index + 1,
      hostName: item.host_name,
      totalValue: parseFloat(item.total_value),
      recordCount: parseInt(item.record_count),
      hallCount: parseInt(item.hall_count),
      averageValue: parseFloat((item.total_value / item.record_count).toFixed(2))
    }));

    res.json({
      period,
      sortBy,
      count: result.length,
      rankings: result
    });
  } catch (error) {
    console.error('获取主持人排行榜失败:', error);
    res.status(500).json({ error: '获取排行榜数据失败: ' + error.message });
  }
}

async function getOverallRankings(req, res) {
  try {
    const { period = 'week' } = req.query;
    
    let timeCondition = '';
    const now = new Date();
    const pastDate = new Date();
    
    switch (period) {
      case 'day':
        pastDate.setDate(now.getDate() - 1);
        break;
      case 'week':
        pastDate.setDate(now.getDate() - 7);
        break;
      case 'month':
        pastDate.setMonth(now.getMonth() - 1);
        break;
      case 'year':
        pastDate.setFullYear(now.getFullYear() - 1);
        break;
      default:
        break;
    }
    
    if (period !== 'all') {
      timeCondition = `WHERE upload_time >= '${pastDate.toISOString()}'`;
    }

    // 按照单条数据的data_value进行排序
    const query = `
      SELECT 
        hall_name,
        host_name,
        data_value,
        upload_time,
        host_hall
      FROM data_records
      ${timeCondition}
      ORDER BY data_value DESC
    `;

    const [rankings] = await pool.query(query);

    const result = rankings.map((item, index) => ({
      rank: index + 1,
      hallName: item.hall_name,
      hostName: item.host_name,
      dataValue: parseFloat(item.data_value),
      uploadTime: item.upload_time,
      hostHall: item.host_hall
    }));

    res.json({
      period,
      count: result.length,
      rankings: result
    });
  } catch (error) {
    console.error('获取综合排行榜失败:', error);
    res.status(500).json({ error: '获取综合排行榜数据失败: ' + error.message });
  }
}

module.exports = {
  getHallRankings,
  getHostRankings,
  getOverallRankings
};